package cn.com.main;

import cn.com.utils.MachineTranslationUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;

import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 用于国际化文件生成与内容替换
 *
 * @author LiuGuodong
 * @date 2024/04/12
 */
@Slf4j
public class Internationalization {

    /**
     * 消息密钥映射
     */
    private static final Map<String, AbnormalInformation> MSG_KEY_MAP = new ConcurrentHashMap<>();

    public static final String TEMPLATE = "    /**\n" +
            "     * %s\n" +
            "     */\n" +
            "    String %s = \"%s\";\n";

    // 项目名
    public static final String MODULE = "BSS";
    // 异常信息类名
    public static final String MSG_CLASS_NAME = "MsgCd";
    // 工具类
    public static final String WEB_UTIL_GET_MESSAGE = "WebUtil.getMessage(";

    public static final String ERR_MSG = "ERR_MSG_" + MODULE + "_";
    public static final String PATH = "E:\\cloud_star\\240108浦发银行项目\\aksk 接口\\Ak_SK_demo\\Ak_SK_demo\\src\\main\\";

    public static void main(String[] args) {
        // 处理目录
        String directoryPath = PATH + "java\\";
        // 匹配的关键字
        String key = "throw new ";
        // 处理异常信息
        replaceCorrespondingException(directoryPath, key);
        // 生成国际化文件
        generateI18nFiles();
    }

    private static void generateI18nFiles() {
        List<String> msgClass = new ArrayList<>();

        List<String> chineseTemplate = new ArrayList<>();
        List<String> englishTemplate = new ArrayList<>();
        MSG_KEY_MAP.forEach((k, v) -> {
            chineseTemplate.add(v.getMsgValue() + "=" + v.getChinese());
            englishTemplate.add(v.getMsgValue() + "=" + v.getEnglish());
            msgClass.add(String.format(TEMPLATE, v.getChinese(), k, v.getMsgValue()));
        });
        writer(Paths.get(MSG_CLASS_NAME + ".txt"), msgClass);
        String path = PATH + "resources\\messages_zh_CN.properties";
        writeI18n(PATH + "resources\\messages_zh_CN.properties", chineseTemplate);
        writeI18n(PATH + "resources\\messages_en_US.properties", englishTemplate);
    }

    private static void writeI18n(String path, List<String> chineseTemplate) {
        // 写入properties文件
        try {
            List<String> allLines = Files.readAllLines(Paths.get(path));
            allLines.addAll(chineseTemplate);
            allLines = allLines.stream().distinct().collect(Collectors.toList());
            writer(Paths.get(path), allLines, StandardOpenOption.WRITE);
        } catch (IOException e) {
            log.error("读取properties文件异常: {}", e.getMessage());
        }
    }

    /**
     * 提取内容 : throw new RetryException(WebUtil.getMessage(MsgCd.ERR_MSG_BSS_2));
     * 转换为:  throw new BizException(WebUtil.getMessage(MsgCd.MES_1));
     *
     * @param errorMessage 错误消息
     * @return {@link String}
     */
    private static String handle(String errorMessage) {
        String replace = errorMessage;
        // 使用正则表达式匹配引号中的内容
        Pattern pattern = Pattern.compile("\"(.*?)\"");
        Matcher matcher = pattern.matcher(errorMessage);
        while (matcher.find()) {
            // 翻译并生成key 保存 key 与中英文的映射
            String group = matcher.group(1);
            if (StrUtil.isBlank(group)) {
                continue;
            }
            String english = MachineTranslationUtil.toEnglish(group);

            String chinese;
            if (MachineTranslationUtil.itsChinese(group)) {
                chinese = group;
            } else {
                chinese = MachineTranslationUtil.toChinese(english);
            }
            String msgkey = ERR_MSG + Math.abs(chinese.hashCode());
            String msgValue = String.join(".", msgkey.toLowerCase().split("_"));
            MSG_KEY_MAP.put(msgkey, new AbnormalInformation(english, msgValue, chinese));
            String key = WEB_UTIL_GET_MESSAGE + MSG_CLASS_NAME + "." + msgkey + ")";
            replace = replace.replace("\"" + group + "\"", key);

        }
        //返回被替换的字符串比如 throw new BizException(WebUtil.getMessage(MsgCd.MES_1));
        return replace;
    }

    public static void replaceCorrespondingException(String directoryPath, String key) {

        try {
            List<Path> collect = Files.walk(Paths.get(directoryPath))
                    .filter(Files::isRegularFile).collect(Collectors.toList());
            for (Path filePath : collect) {
                File file = filePath.toFile();
                if (file.getName().endsWith(".java")) {
                    try {
                        Path path = file.toPath();
                        List<String> updatedLines = replace(key, Files.readAllLines(path));
                        // 保存
                        writer(path, updatedLines, StandardOpenOption.WRITE);
                    } catch (IOException e) {
                        System.err.println("Error reading file: " + file.getAbsolutePath() + ": " + e.getMessage());
                    }
                }
            }

        } catch (Exception e) {
            System.err.println("Error scanning directory: " + directoryPath + ": " + e.getMessage());
        }
    }

    private static @NotNull List<String> replace(String key, List<String> allLines) {
        if (CollectionUtil.isEmpty(allLines)) {
            return allLines;
        }
        return allLines.parallelStream().map(line -> {
            if (StrUtil.isBlank(line)) {
                return line;
            }
            // 匹配需要替换的代码
            if (line.contains(key) && line.contains("\"") && line.contains("(")) {
                line = handle(line);
            }
            return line;
        }).collect(Collectors.toList());
    }

    private static void writer(Path path, List<String> inputList, OpenOption... options) {
        try (BufferedWriter writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8, options)) {
            for (String line : inputList) {
                if (StrUtil.isNotBlank(line)) {
                    writer.write(line);
                }
                writer.newLine();
            }
        } catch (Exception e) {
            log.error("写入文件异常: {}", e.getMessage());
        }
    }

    /**
     * 异常信息
     *
     * @author LiuGuodong
     * @date 2024/04/15
     */
    @Data
    @AllArgsConstructor
    private static class AbnormalInformation {
        private String english;
        private String msgValue;
        private String chinese;

    }
}
